#include "stdafx.h"
#include "DataSession.h"
#include <iostream>
#include "boost/bind.hpp"

DataSession::DataSession( boost::asio::io_service &svcIO)
:m_theSvcIO(svcIO), m_theSocket(svcIO), m_wpMsgBufferFactory(NULL)
{
}

int
DataSession::getID()const
{
	return m_nSesId;
}

void
DataSession::setID(int nID)
{
	m_nSesId = nID;
}

boost::asio::ip::tcp::socket&
DataSession::getSocket()
{
	return m_theSocket;
}

bool
DataSession::read(MsgBuffer* pStream)
{
	if (pStream==NULL)
	{
		pStream = m_wpMsgBufferFactory->malloc();
	}

	if (pStream)
	{
		boost::asio::async_read(m_theSocket,
			pStream->prepare(1024),
			boost::bind(&DataSession::onInput, this, boost::asio::placeholders::error, pStream));
	}

	return true;
}


bool
DataSession::write(MsgBuffer* pStream)
{
	if (pStream)
	{
		boost::asio::async_write(m_theSocket,
			pStream->data(),
			boost::bind(&DataSession::onOutput, this, boost::asio::placeholders::error, pStream));
	}

	return true;
}

void
DataSession::setDataStreamPool(MsgBufferFactory* pMsgBuffFact)
{
	m_wpMsgBufferFactory = pMsgBuffFact;
}

bool
DataSession::onUpdate(const int& nElapse)
{
	return true;
}

void 
DataSession::onInput(const boost::system::error_code& error, MsgBuffer* pStream )
{
	if (!error)
	{
		

		read();
	}
	else
	{
		std::cout<<"Error!"<<std::endl;
	}
}

void
DataSession::onOutput(const boost::system::error_code& error, MsgBuffer* pStream )
{
	if (pStream)
	{
		//	recycle
		m_wpMsgBufferFactory->free(pStream);
	}
}
